﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;

public partial class modules_categories_v2 : System.Web.UI.UserControl
{
    // CSS Properties
    public int BoxTemplate = 0; // Default,
    public string BoxCssClass = ""; // main box css style
    public string HeadingCssClass = ""; // main box heading css style
    public string BodyCssClass = ""; // main body section css style
    public string CssClass = ""; // Provide link css class
    public string ActiveCssClass = "bld_01"; // provide active link css class
    public string ListingCssClass = "ver_lst";
    // New Properties
    public bool isMainNavigation = false; // true if you want to generate main navigations
    public bool isHeading = true; // Enable / Disable Heading
    public string HeadingTitle = "Categories";
    public bool ShowParentsOnly = false; // Show Only Parent Categories
    public string MoreLinkUrl = "";
    public string MoreLinkText = "";
    public string LinkToolTip = "";
    public string MoreLinkToolTip = "";
    public bool MainCategoryURL = true; // main category for all contents or redirect user to specific content category url.
    public bool isHierarchy = true; // display links in parent child hirarchy
    public bool showCounter = false; // display number of records exist in each category
    public bool MultiColumn = false;
    public int TotalColumns = 1;
    public int Mode = 0; // Group certain categories via mode e.g in case of cars groups categories like "Car Brands, Auto Shows, Vehicle Types, Vehicle Styles" etc
    public int ParentID = 0;
    public string Order = "priority desc, categoryname asc";
    public int Type = 0; // 0: videos, 1: groups, 2: channels, 4: abuse reports, 5: photos 6: blogs 7: audio files, 8: galleries, 12 forum
    public int Total_Records = 30;
    public bool isAll = false;
    // Version 2.0 Properties
    public string NavigationCssClass = "c_lst";
    public int TotalParents = 0; //0: unlimited
    public int TotalChilds = 0; // 0: unlimited (list of child categories within each parent item)
    public string UlParentCssClass = ""; // used in case of menu
    public string UlChildCssClass = ""; // used in case of menu
    public string URL = "";
    public string Value = ""; // Custom Value e.g <span>[CN]</span>[CT],[CID] where [CN] -> category name, [CT] -> term and [CID] -> category id
    public int RepeatDirection = 0; // 0: vertical, 1: horizontal (in case of multiple column approach is used
    public string ColumnWidth = "25%"; // width of each column in case of multiple column listing
    public string DirectoryBoxCssClass = "";
    public string ParentCssClass = ""; // parent category link css class
    public string ParentBoxCssClass = ""; // parent category div css class in case of directory listing
    public string ChildBoxCssClass = ""; // Child category listing div css class in case of directory listing

    // Private Properties (Internal Use Only)
    private int _parentcatcounter = 0;
    private int _childcatcounter = 0;
    private bool _skip = false; // child skip flag
    private bool _parentskip = false; // parent skip flag
    private int _columnrecords = 0; // records to be shown in each column
    private int _columncounter = 0;
    private int _horcolumncounter = 0;
    private int Counter = 1;
    private bool isStop = false; // stop recursive processing of category listing
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (this.BoxCssClass == "" && !this.isMainNavigation)
            PrepareBoxTemplates();

        if (!Page.IsPostBack)
        {
            if (this.isHeading)
            {
                hd.Attributes.Add("class", HeadingCssClass);
                htitle.InnerHtml = this.HeadingTitle;
            }
            else
                hd.Visible = false;

            BindList(this.ParentID);
        }
    }


    private void BindList(int parentid)
    {
        StringBuilder str = new StringBuilder();
        int category_type = this.Type;
        if (category_type == 8) // gallery 
            category_type = 5; // photos and gallery load same type of categories.
        if (this.isHierarchy)
        {
            string navcss = "";
            if (this.NavigationCssClass != "")
                navcss = "class=\"" + this.NavigationCssClass + "\"";
            str.Append("<div " + navcss + ">\n");
        }
        if (!MultiColumn)
        {
            // Single Column Listing
            LoadCategories(parentid, str, category_type, this.isAll, this.Total_Records);
        }
        else
        {
            // Multiple Column Listing
            if (this.ShowParentsOnly)
            {
                // Only parent categories to be shown
                if (this.RepeatDirection == 0)
                {
                    // vertical direction
                    // Count total parent categories
                    int countparents = CategoriesBLL.Count(parentid, this.Type, 0);
                    if (countparents > 0)
                    {
                        _columnrecords = ((int)countparents / this.TotalColumns) + 1;
                        LoadCategories(parentid, str, category_type, this.isAll, this.Total_Records);
                    }
                }
                else
                {
                    // horizontal direction // Require inline listing css class
                    LoadCategories(parentid, str, category_type, this.isAll, this.Total_Records);
                }
            }
            else
            {
                // Parent Child Both To Be Shown In Multi Column Layout Structure
                LoadCategories_Advance(parentid, str, category_type, this.isAll, this.Total_Records);
            }
        }
        if (this.isHierarchy)
            str.Append("</div>\n");
        str.Append("<div class=\"clear\"></div>");
        lst.InnerHtml = str.ToString();
        lst.Attributes.Add("class", this.BodyCssClass + " ui-helper-clearfix");
    }

    // Core Script To Generate Normal Category Listings (Single or Multi Line)
    private void LoadCategories(int parentid, StringBuilder str, int tp, bool isall, int records)
    {        
        string _ulcsslass="";
        if (parentid == 0)
        {
            // main menu
            if (this.UlParentCssClass != "")
                _ulcsslass = " class=\"" + this.UlParentCssClass + "\"";
        }
        else
        {
            // sub menus
            if (this.UlChildCssClass != "")
                _ulcsslass = " class=\"" + this.UlChildCssClass + "\"";
        }
     
        List<Category_Struct_V2> _lst = CategoriesBLL.Load_CategoriesSummary(parentid, tp, isall, 0, this.Mode, Order, records, 1);
        if (_lst.Count > 0)
        {
            if (_columnrecords > 0)
            {
                // multipl column listing is enabled
                str.Append("<div style=\"float:left; width:" + this.ColumnWidth + ";\">\n");
            }
            str.Append("\n<ul" + _ulcsslass + ">\n");
            int i = 0;
            for (i = 0; i <= _lst.Count - 1; i++)
            {
                if (parentid==0 && this.TotalParents > 0)
                {
                    _parentcatcounter++;
                }

                if (this.TotalChilds > 0 && parentid>0 && !_skip)
                {
                    _childcatcounter++;
                }
  
                if (parentid == 0)
                {
                    _skip = false;
                    if (_parentskip)
                        return; // break further generating category list
                }

                if (_columncounter >= _columnrecords && _columnrecords > 0)
                {
                    // in case of multiple column listing if specified record level reached in single column
                    _columncounter = 0;
                    str.Append("</ul>\n");
                    str.Append("</div>\n");
                    str.Append("<div style=\"float:left; width:" + this.ColumnWidth + ";\">\n");
                    str.Append("\n<ul" + _ulcsslass + ">\n");
                }

                if (_horcolumncounter >= this.TotalColumns)
                {
                    _horcolumncounter = 0;
                    str.Append("</ul>\n");
                    str.Append("\n<ul" + _ulcsslass + ">\n");
                }
                
              


                if (!_skip) // if skip is enabled, leave adding listing
                {
                    string _linkcssclass = this.CssClass;
                    if (parentid == 0)
                    {
                        if(this.ParentCssClass!="")
                            _linkcssclass = this.ParentCssClass;
                    }
                    str.Append("<li>" + Prepare_Category_Url(_lst[i].CategoryID, _lst[i].CategoryName.ToString(), _lst[i].Term.ToString(), _lst[i].Records, _linkcssclass));
                }

                if (parentid == 0 && this.TotalParents > 0)
                {                 
                    if (_parentcatcounter >= this.TotalParents)
                    {
                        _parentskip = true; // enable parent skip
                        _parentcatcounter = 0;
                    }
                }

                if (this.TotalChilds > 0 && parentid > 0)
                {
                    if (_childcatcounter >= this.TotalChilds)
                    {
                        _skip = true; // skip listing until next parent category comes
                        _childcatcounter = 0;
                    }
                }
                
                // check for child 
                if (!this.ShowParentsOnly)
                {                   
                    if (CategoriesBLL.Has_Child(_lst[i].CategoryID, 0))
                    {
                       LoadCategories(_lst[i].CategoryID, str, tp, isall, records);
                    }
                }
                str.Append("</li>\n");
                Counter++;
                if (!isall && Counter > this.Total_Records && this.MoreLinkUrl != "")
                {
                    // generate more link
                    str.Append("<li><a href=\"" + Config.GetUrl(this.MoreLinkUrl) + "\" class=\"" + this.CssClass + "\" title=\"" + this.MoreLinkToolTip + "\">" + this.MoreLinkText + "</a></li>\n");
                    if (!isStop)
                        isStop = true;
                    return;
                }
                if (isStop)
                    return;
                if(_columnrecords>0) // vertical column counter
                    _columncounter++;
                if (this.MultiColumn && this.RepeatDirection == 1) // horizontal column counter
                    _horcolumncounter++;

               
                
            }
            str.Append("</ul>\n");
            if (_columnrecords > 0)
            {
                str.Append("</div>\n");
                str.Append("<div class=\"clear\"></div>\n");
            }
        }
       
      
    }

    // Core Script To Generate Advance Category Listings (Directory Structure)
    private void LoadCategories_Advance(int parentid, StringBuilder str, int tp, bool isall, int records)
    {      
        string _ulcssclass = "";
        List<Category_Struct_V2> _lst = CategoriesBLL.Load_CategoriesSummary(parentid, tp, isall, 0, this.Mode, Order, records, 1);
        if (_lst.Count > 0)
        {
            if (parentid == 0)
            {
                string _directorycssboxcss = "";
                if (this.DirectoryBoxCssClass != "")
                    _directorycssboxcss = "style=\"width:" + this.ColumnWidth + ";float:left;\" class=\"" + DirectoryBoxCssClass + "\"";
                else
                    _directorycssboxcss = "style=\"width:" + this.ColumnWidth + ";float:left;\"";
                str.Append("<div " + _directorycssboxcss + ">\n");
            }
            else
            {
                if (this.UlParentCssClass != "")
                    _ulcssclass = " class=\"" + this.UlParentCssClass + "\"";
                string _childboxcssclass = "";
                if (this.ChildBoxCssClass != "")
                    _childboxcssclass = " class=\"" + this.ChildBoxCssClass + "\"";
                str.Append("<div" + _childboxcssclass + ">\n");
                str.Append("<ul" + _ulcssclass + ">\n");
            }
            int i = 0;
            for (i = 0; i <= _lst.Count - 1; i++)
            {
                string _linkcssclass = this.CssClass;
                if (parentid == 0)
                {
                    if (this.ParentCssClass != "")
                        _linkcssclass = this.ParentCssClass;
                }

                if (parentid == 0 && this.TotalParents > 0)
                {
                    _parentcatcounter++;
                }

                if (this.TotalChilds > 0 && parentid > 0 && !_skip)
                {
                    _childcatcounter++;
                }

                string _categoryurl = Prepare_Category_Url(_lst[i].CategoryID, _lst[i].CategoryName.ToString(), _lst[i].Term.ToString(), _lst[i].Records, _linkcssclass);
                if (parentid == 0)
                {
                    string _parentboxcssclass = "";
                    if (this.ParentBoxCssClass != "")
                        _parentboxcssclass = " class=\"" + this.ParentBoxCssClass + "\"";
                    str.Append("<div" + _parentboxcssclass + ">\n");
                    str.Append(_categoryurl + "\n");
                    str.Append("</div>\n");
                }
                else
                {
                    if (!_skip) // if skip is enabled, leave adding listing
                    {
                        str.Append("<li>" + _categoryurl);
                    }
                }
              
                if (this.TotalChilds > 0 && parentid > 0)
                {
                    if (_childcatcounter >= this.TotalChilds)
                    {
                        _skip = true; // skip listing until next parent category comes
                        _childcatcounter = 0;
                    }
                }
                if (CategoriesBLL.Has_Child(_lst[i].CategoryID, 0))
                {
                    LoadCategories_Advance(_lst[i].CategoryID, str, tp, isall, records);
                }

                if(parentid>0)
                {
                    if (!_skip) // if skip is enabled, leave adding listing
                    {
                        str.Append("</li>\n");
                    }
                }

                if (parentid == 0 && this.TotalParents > 0)
                {
                    if (_parentcatcounter >= this.TotalParents)
                    {
                        _parentskip = true; // enable parent skip
                        _parentcatcounter = 0;
                    }
                }

                if (parentid == 0)
                {
                    _skip = false;
                    if (_parentskip)
                        return; // break further generating category list
                }

            }
            if (parentid == 0)
            {
                str.Append("</div>\n");
            }
            else
            {
                if (this.TotalChilds > 0)
                {
                    _skip = false; // reset skip false if its enabled
                    _childcatcounter = 0; // reset child counter
                }
                str.Append("</ul>\n");
                str.Append("</div>\n"); // close listing div
                str.Append("</div>\n"); // close box div
                _columncounter++;
                if (_columncounter >= this.TotalColumns)
                {
                    _columncounter = 0;
                    str.Append("<div class=\"clear\"></div>\n");
                }
                string _directorycssboxcss = "";
                if (this.DirectoryBoxCssClass != "")
                    _directorycssboxcss = "style=\"width:" + this.ColumnWidth + ";float:left;\" class=\"" + DirectoryBoxCssClass + "\"";
                else
                    _directorycssboxcss = "style=\"width:" + this.ColumnWidth + ";float:left;\"";
                str.Append("<div " + _directorycssboxcss + ">\n");
            }

           
        }
     
    }

    private string Prepare_Category_Url(int categoryid, string categoryname, string term, int records, string cssclass)
    {
        string _cssclass = "";
        StringBuilder str = new StringBuilder();
        string cname = UtilityBLL.UppercaseFirst(categoryname.Trim(), true);
        str.Append("<a href=\"");
        if (this.URL != "")
            str.Append(Parse_Category_URL(this.URL,categoryname,term,categoryid));
        else
            str.Append(UrlConfig.Prepare_Category_Url(categoryid, categoryname, term, this.Type, this.MainCategoryURL));
        str.Append("\"");

        if (cssclass != "")
            _cssclass = "class=\"" + cssclass + "\"";
        str.Append(" " + _cssclass);
       
        string _tooltip = cname.Trim();
        if (this.LinkToolTip.Trim() != "")
            _tooltip = cname + " " + this.LinkToolTip.Trim();

        str.Append("title=\"" + _tooltip + "\"");
        if (this.Value != "")
            str.Append(">" + Parse_Category_Info(this.Value,categoryname,term,categoryid));
        else
           str.Append(">" + categoryname.Trim());
        if (this.showCounter)
            str.Append(" (" + records + ")");
    
        str.Append("</a>");
        return str.ToString();
    }

    private void PrepareBoxTemplates()
    {
        this.BoxCssClass = "module ui-corner-all";
        this.HeadingCssClass = "heading";
    }

    // replace [CN], [CT], [CID] with categoryname, term and categoryid
    public string Parse_Category_Info(string input, string categoryname, string term, int categoryid)
    {
        input = Regex.Replace(input, @"\[CN\]", categoryname);
        input = Regex.Replace(input, @"\[CT\]", term);
        return Regex.Replace(input, @"\[CID\]", categoryid.ToString());
    }

    // replace [CT] with term or categoryname, [CID] with categoryid
    public string Parse_Category_URL(string input, string categoryname, string term, int categoryid)
    {
        if (term == "")
            term = categoryname;

        input = Regex.Replace(input, @"\[CN\]", UtilityBLL.ReplaceSpaceWithHyphin_v2(term.Trim().ToLower()));
        return Regex.Replace(input, @"\[CID\]", categoryid.ToString());
    }
}